alter TRIGGER [dbo].[trgAfterInsert]     
ON  [dbo].[LeadStatus]     
AFTER INSERT  
AS   
BEGIN   
-- SET NOCOUNT ON added to prevent extra result sets from   
-- interfering with SELECT statements.   
SET NOCOUNT ON;   
declare @purchaseorderID int;   
declare @leadid int;   
declare @CallCentreID int;   
declare @LeadStatusID int;   
declare @Replacement bit;      
select @CallCentreID=i.CallCentreID from inserted i;   
select @leadid=i.leadid from inserted i;   
select @LeadStatusID=i.leadstatusid from inserted i;      
select top 1 @purchaseorderID=purchaseorderid 
	from purchaseorders 
	where leadid=@leadid and callcentreid=@callcentreid and 
		(deficit>0 or deficit is null)     
		and rejected>(replaced+invalidreturns) and visible=1 and clientpaid=1
	order by weekending;       
if(@purchaseorderID is not null)    
begin     
	set @Replacement=1;    
end   
else    
begin     
	select @purchaseorderID=purchaseorderid 
	from purchaseorders 
	where leadid=@leadid and callcentreid=@callcentreid and (deficit>0 or deficit is null) and visible=1 and clientpaid=1;     
	set @Replacement=null;    
end   
update dbo.leadstatus set purchaseorderid=@purchaseorderID, replacement=@Replacement, sysgen=1 
	where leadstatusid=@LeadStatusID;        
END  